package com.ssm.sport.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssm.sport.entity.Category;
import com.ssm.sport.mapper.CategoryMapper;
import com.ssm.sport.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品分类服务实现类
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public List<Category> getTopCategories() {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", 0)  // 顶级分类的parent_id为0
                   .eq("status", 1)      // 状态正常
                   .orderByAsc("sort");  // 按排序字段升序
                   
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<Category> getChildCategories(Integer parentId) {
        if (parentId == null || parentId < 0) {
            return new ArrayList<>();
        }
        
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId)
                   .eq("status", 1)
                   .orderByAsc("sort");
                   
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<Category> getCategoryTree() {
        // 获取所有状态正常的分类
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1)
                   .orderByAsc("sort");
                   
        List<Category> allCategories = baseMapper.selectList(queryWrapper);
        
        // 按照parentId分组
        Map<Integer, List<Category>> parentIdMap = allCategories.stream()
                .collect(Collectors.groupingBy(Category::getParentId));
        
        // 构建树形结构
        List<Category> rootCategories = parentIdMap.getOrDefault(0, new ArrayList<>());
        rootCategories.forEach(category -> buildChildren(category, parentIdMap));
        
        return rootCategories;
    }
    
    /**
     * 递归构建子分类
     */
    private void buildChildren(Category parent, Map<Integer, List<Category>> parentIdMap) {
        List<Category> children = parentIdMap.getOrDefault(parent.getId(), new ArrayList<>());
        parent.setChildren(children);
        children.forEach(child -> buildChildren(child, parentIdMap));
    }
} 